package com.csmht.tododemo.interceptor;

import com.csmht.tododemo.pojo.entity.Role;
import com.csmht.tododemo.pojo.enumeration.RoleEnum;
import com.csmht.tododemo.properties.JwtProperties;
import com.csmht.tododemo.until.BaseUnit;
import com.csmht.tododemo.until.JwtUntil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static com.csmht.tododemo.pojo.entity.Role.convertToRole;

@Component
@Slf4j
@Order(1)
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //requestDispatcherPath

        if(true){
            BaseUnit.setCurrentId(Role.builder().id(1L).role(RoleEnum.ADMIN).build());
            return true;
        }

        log.info("jwtURL:{}",request.getRequestURI());

        if(Objects.equals(request.getRequestURI(), "/admin/todo")){
            log.info("插入数据");
        }

        String requestURI = request.getRequestURI();

        List<String> list = new ArrayList<>();

        list.add(".html");
        list.add("/login");
        list.add("/enroll");

        for (String s : list) {
            if(requestURI.contains(s)){
                return true;
            }
        }

        if(request.getMethod().equals("OPTIONS")){
            return true;
        }

        String token = request.getHeader(jwtProperties.getTokenName());

        if(Objects.equals(token, "csmht")){



            BaseUnit.setCurrentId(Role.builder().id(1L).role(RoleEnum.ADMIN).build());
            return true;
        }

        if(Objects.equals(token, "csmht1")){
            BaseUnit.setCurrentId(Role.builder().id(4L).role(RoleEnum.USER).build());
            return true;
        }


        try {
            Claims claims =  JwtUntil.parseJWT(jwtProperties.getSecretKey(),token);
            Object user = claims.get("role");

            Role role = convertToRole(user);

            BaseUnit.setCurrentId(role);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            log.error(e.toString());
            return false;
        }
    }
}
